package com.tjbklx1.thread.chap04.demo02;

import java.util.concurrent.TimeoutException;

/**
 * guarded timeout 在条件成立之前，等一段时间
 * @author Administrator
 *
 */
public class Host {

	private final long timeout;
	private boolean ready = false; // 默认FALSE

	public Host(long timeout) {
		super();
		this.timeout = timeout;
	}

	public synchronized void setExecutable(boolean on) {
		ready = on;
		notifyAll();
	}

	public synchronized void execute() throws TimeoutException, InterruptedException {
		long start = System.currentTimeMillis();
		while (!ready) {
			long now = System.currentTimeMillis();
			long rest = timeout - (now - start);
			if (rest <= 0) {
				throw new TimeoutException("now - start = " + (now - start) + ", timeout " + timeout);
			}
			wait(rest);
		}
		doExecute();
	}

	private void doExecute() {
		System.out.println(Thread.currentThread().getName() + " calls doExecute.");
	}

}
